﻿var queryYm='0000-00';
var ValueCardPay = function (targetObj) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.dateFormat = "yyyy-MM";
    this.init();
    return this;
}

ValueCardPay.prototype = {
    init: function () {
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName: 'search_btn', fs: this.findReport},
            {fName: 'reset_btn', fs: this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null, bindFieldArray, bindFunctionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.targetObj, this);
        //this.initDatePick();
        var date = new Date();
        this.sysUtils.mvvmModel.set("YearMth",kendo.toString(date,this.dateFormat));
        this.findReport();
    },
    findReport:function (e) {
        var that = this;
        if (isNotEmpt(e)) {
            that = $(e.target).data("that");
        }
        if (validityForm(that.targetObj)) {
            var param = that.sysUtils.getBindDocJson(that.bindBaseModels.bindFieldArray);
            //转换时间格式
            if (isNotEmpt(param["YearMth"])) {
                param["YearMth"] = kendo.toString(param["YearMth"], 'yyyy-MM');
                queryYm = param["YearMth"];
            }
            JsonpAjax(baseApiPath+"report/valueCard",JSON.stringify(param),"json",function(result){
                //构建列表
                that.initTable(result);
            });
        }
    },
    resetInfo:function (e) {
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
        var date = new Date();
        that.sysUtils.mvvmModel.set("YearMth",kendo.toString(date,that.dateFormat));
    },

    initTable:function (result) {
        debugger
        var that = this;
        var days = result.days;
        var now = result.now;
        that.initTableBefore(days);
        var list = result.results;
        var tbody = that.targetObj.find("#valueCardTb > tbody");
        //当前时间月份是否大于查询月份
        var nextMonth = that.compareYearMonth(queryYm,now.substring(0,7));
        if(!isEmpty(list)){
            var box = that.variantData(list);
            var boxsize = box.length;
            debugger
            for(var b=0;b<boxsize;b++){//车主
                var tr=$("<tr></tr>");
                var vehicle = box[b].data;
                var velen = vehicle.length;
                tr.append($("<td rowspan='"+(3*velen)+"'>"+box[b].ownerName+"</td>"));
                for(var v=0;v<velen;v++){//车牌
                    if(v!=0){
                        tr=$("<tr></tr>")
                    }
                    tr.append($("<td rowspan='3'>"+vehicle[v].vehicleNo+"</td>"));

                    var veDetail = vehicle[v].data;
                    var delen = veDetail.length;


                    tr.append($('<td>时长</td>'));
                    var moneyTr = $("<tr></tr>");
                    moneyTr.append($('<td>金额</td>'));
                    var subCount = $("<tr></tr>");

                    var subDays = 0,subMoney = 0,totalTime=0;
                    var arr = new Array();

                    for(var e=0;e<delen;e++){//车牌进出进入
                        var detail = veDetail[e];
                        var status = detail.recodeStatus;
                        var inRecode = {time:detail.inTime,day:detail.inDay};
                        arr.push(inRecode);
                        if(status==1){
                            var outRecode = {time:detail.outTime,day:detail.outDay,status:status,money:detail.chargeMoney};
                            arr.push(outRecode);
                        }
                    }
                    //that.quickSort(arr);

                    for(var d=1;d<=days;d++){
                        var retValue=that.findDataByDay(arr,d,now,nextMonth);
                        tr.append($('<td>'+retValue.stopTime+'</td>'));
                        moneyTr.append($('<td>'+retValue.money+'</td>'));
                        totalTime+=retValue.stopTime;
                        subDays+=retValue.stopDay;
                        subMoney+=parseFloat(retValue.money);
                    }
                    var miTd=$("<td colspan='"+(days+1)+"' style='text-align:center'></td>");
                    miTd.append($("<label style='font-weight:bold'>月停比：</label><span class='fontRed mr10'>"+subDays+"/"+days+"</span>"));
                    miTd.append($("<label style='font-weight:bold'>临停时长：</label><span class='fontRed mr10'>"+totalTime+"分钟</span>"));
                    miTd.append($("<label style='font-weight:bold'>消费：</label><span class='fontRed mr10'>"+subMoney.toFixed(2)+"元</span>"));
                    subCount.append(miTd);
                    //tr.append(timeTr);
                    //tr.append(timeTr);
                    tbody.append(tr);
                    tbody.append(moneyTr);
                    tbody.append(subCount);
                }
            }

        }else{
            tbody.append($("<tr><td colspan='"+(3+days)+"' style='text-align:center;'>未查询到数据</td></tr>"));
        }
    },
    GetDateTimeDiff:function (date) {
        date=date<0?-date:date;
        //计算出相差天数
        var days = Math.floor(date / (24 * 3600 * 1000));

        //计算出小时数

        var leave1 = date % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000));
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000);     //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000));
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000);  //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000);
        var addMin = 0;
        if(seconds>0){
            addMin=1;
        }
        return date<0?-(days * 24*60 + hours*60+ minutes + addMin):(days * 24*60 + hours*60+ minutes + addMin);
    },
    initTableBefore:function (days) {
        var that = this;
        var table = that.targetObj.find("#valueCardTb");
        table.empty();
        var tr=$("<tr></tr>");
        tr.append($("<th>车主</th>"));
        tr.append($("<th>车牌</th>"));
        tr.append($("<th>时长/金额</th>"));
        for(var d=1;d<=days;d++){
            tr.append($("<th>"+d+"日</th>"));
        }
        //tr.append($("<th>合计</th>"));
        table.append(tr);
    },
    /**
     * 换个姿势刷数据
     * @param list
     */
    variantData:function (list) {
        var length = list.length;
        //车主车牌分组
        var mapf = {},destf = [];
        for (var i = 0; i < length; i++) {
            var owner = list[i];
            if (!mapf[owner.ownerCode]) {
                destf.push({
                    ownerCode: owner.ownerCode,
                    ownerName: owner.ownerName,
                    data: [owner]
                });
                mapf[owner.ownerCode] = owner;
            } else {
                for (var j = 0; j < destf.length; j++) {
                    var dj = destf[j];
                    if (dj.ownerCode == owner.ownerCode) {
                        dj.data.push(owner);
                        break;
                    }
                }
            }
        }
        length=destf.length;
        for (var i = 0; i < length; i++) {
            var data = destf[i].data;
            var size = data.length;
            //车牌统计分组
            var maps = {},dests = [];
            for (var j = 0; j < size; j++) {
                var cardPay = data[j];
                if (!maps[cardPay.vehicleNo]) {
                    dests.push({
                        vehicleNo: cardPay.vehicleNo,
                        data: [cardPay]
                    });
                    maps[cardPay.vehicleNo] = cardPay;
                } else {
                    for (var l = 0; l < dests.length; l++) {
                        var dj = dests[l];
                        if (dj.vehicleNo == cardPay.vehicleNo) {
                            dj.data.push(cardPay);
                            break;
                        }
                    }
                }
            }
            destf[i].data = dests;
        }
        return destf;
    },
    quickSort:function (arr) {
        var that =this;
        //如果数组长度小于等于1无需判断直接返回即可
        if(arr.length<=1){
            return arr;
        }
        var midIndex=Math.floor(arr.length/2);//取基准点
        var midIndexVal=arr.splice(midIndex,1);//取基准点的值,splice(index,1)函数可以返回数组中被删除的那个数arr[index+1]
        var left=[];//存放比基准点小的数组
        var right=[];//存放比基准点大的数组
        //遍历数组，进行判断分配
        for(var i=0;i<arr.length;i++){
            if(compareTime(arr[i].time,midIndexVal[0].time)){
                left.push(arr[i]);//比基准点小的放在左边数组
            }
            else{
                right.push(arr[i]);//比基准点大的放在右边数组
            }
        }
        //递归执行以上操作,对左右两个数组进行操作，直到数组长度为<=1；
        return that.quickSort(left).concat(midIndexVal,that.quickSort(right));
    },
    compareYearMonth:function (start,end) {
        var startYear = start.split('-')[0];
        var endYear = end.split('-')[0];
        if(parseInt(endYear)>parseInt(startYear)){
            return true
        }else{
            var startMonth = start.split('-')[1];
            var endMonth = end.split('-')[1];
            if(parseInt(endMonth)>parseInt(startMonth)){
                return true;
            }
            return false;
        }
    },
    findDataByDay:function (arr,day,now,nextMonth) {
        var that = this;
        var retValue={};
        retValue.has=false
        var l=arr.length;
        var nowDay = now.substring(0,10);
        var stopTime=0,money=0,stopDay=0;
        //遍历获取匹配日期当天停留数据
        if((''+day).length<2){
            day='0'+day;
        }
        for(var i=0;i<l;i++){
            var obj = arr[i];
            if(obj.day==(queryYm+'-'+day)){
                if(compareDate(nowDay,queryYm+'-'+day)){//列日晚于当前日期
                    stopTime+=0;
                    money+=0;
                    stopDay+=0;
                }else{
                    if(obj.status==undefined){
                        if(arr[i+1]!=undefined){//相对入场的出场点
                            if(compareDate(obj.day,arr[i+1].day)){//不同日
                                var startTime = new Date(obj.time);
                                var endTime = new Date(obj.time);
                                endTime.setDate(endTime.getDate()+1);
                                endTime.setHours(0,0,0,0);
                                stopTime+=that.GetDateTimeDiff(endTime.getTime()- startTime.getTime());
                            }else{
                                var startTime = new Date(obj.time);
                                var endTime = new Date(arr[i+1].time);
                                stopTime+=that.GetDateTimeDiff(endTime.getTime()- startTime.getTime());
                            }
                            stopDay+=1;
                        }else{//未出场
                            //列日早于或等于当前日期
                            if(arr[i].day==nowDay){//前截点与当前日期相等
                                var startTime = new Date(arr[i].time);
                                var endTime = new Date(now);
                                stopTime+=that.GetDateTimeDiff(endTime.getTime()-startTime.getTime());
                                money+=0;
                                stopDay+=1;
                            }else{//前节点日期早于当前日期
                                var startTime = new Date(arr[i].time);
                                var endTime = new Date(arr[i].time);
                                endTime.setDate(endTime.getDate()+1);
                                endTime.setHours(0,0,0,0);
                                stopTime+=that.GetDateTimeDiff(endTime.getTime()-startTime.getTime());
                                money+=0;
                                stopDay+=1;
                            }
                        }
                    }else{
                        if(arr[i-1]!=undefined){//相对出场的入场点
                            if(compareDate(arr[i-1].day,obj.day)){//不同日进出
                                var startTime = new Date(obj.time);
                                var endTime = new Date(obj.time);
                                startTime.setHours(0,0,0,0);
                                stopTime+=that.GetDateTimeDiff(endTime.getTime()- startTime.getTime());
                            }
                            money+=obj.money;
                            stopDay+=1;
                        }
                    }
                }
                /* if(obj.status!=undefined){//出场点
                 if(arr[i-1]!=undefined){//相对出场的入场点
                 if(compareDate(arr[i-1].day,obj.day)){//不同日
                 var startTime = new Date(obj.time);
                 var endTime = new Date(obj.time);
                 startTime.setHours(0,0,0,0);
                 stopTime+=that.GetDateTimeDiff(endTime.getTime()- startTime.getTime());
                 }else{
                 var startTime = new Date(arr[i-1].time);
                 var endTime = new Date(obj.time);
                 stopTime+=that.GetDateTimeDiff(endTime.getTime()- startTime.getTime());
                 }
                 stopDay+=1;
                 money+=obj.money;
                 }

                 }else{//入场点

                 }*/
                retValue.has=true;
            }
        }
        if(retValue.has){
            //如果匹配
            retValue.stopTime=stopTime;
            retValue.money=money>0?money.toFixed(2):0;
            retValue.stopDay=stopDay>0?1:0;
        }else{//未匹配则获取之前的截至点或之后的截点

            if(nextMonth){
                var theStart=-1,theEnd=-1;
                //找头
                for(var i=0;i<l;i++){
                    if(compareDate(arr[i].day,queryYm+'-'+day)){
                        theStart=i;
                    }
                }
                if(theStart>-1){
                    if(arr[theStart].status!=undefined){
                        retValue.stopTime=0;
                        retValue.money=0;
                        retValue.stopDay=0;
                    }else{
                        retValue.stopTime=1440;
                        retValue.money=0;
                        retValue.stopDay=1;
                    }
                }else{
                    //找尾
                    for(var i=0;i<l;i++){
                        if(compareDate(queryYm+'-'+day,arr[i].day)){
                            theEnd=i;
                            break;
                        }
                    }
                    if(theEnd>-1){
                        if(arr[theEnd].status!=undefined){
                            retValue.stopTime=1440;
                            retValue.money=0;
                            retValue.stopDay=1;
                        }else{
                            retValue.stopTime=0;
                            retValue.money=0;
                            retValue.stopDay=0;
                        }
                    }
                }
            }else{
                if(compareDate(nowDay,queryYm+'-'+day)){//列日晚于当前日期
                    retValue.stopTime=0;
                    retValue.money=0;
                    retValue.stopDay=0;
                }else{//列日等于或早于当前日期
                    var theStart=-1;
                    //找头
                    for(var i=0;i<l;i++){
                        if(compareDate(arr[i].day,queryYm+'-'+day)){
                            theStart=i;
                        }
                    }
                    if(theStart>-1){
                        if(arr[theStart].status!=undefined){//出场后很安静，不耗时不消费
                            retValue.stopTime=0;
                            retValue.money=0;
                            retValue.stopDay=0;
                        }else{//处于入场之后，耗时但费用未出
                            if(nowDay==(queryYm+'-'+day)){//列日与当前日期相等
                                if(arr[theStart].day==nowDay){//前截点与当前日期相等
                                    var startTime = new Date(arr[theStart].time);
                                    var endTime = new Date(now);
                                    retValue.stopTime=that.GetDateTimeDiff(endTime.getTime()-startTime.getTime());
                                    retValue.money=0;
                                    retValue.stopDay=1;
                                }else{//前节点日期早于当前日期
                                    var startTime = new Date(now);
                                    var endTime = new Date(now);
                                    startTime.setHours(0,0,0,0);
                                    retValue.stopTime=that.GetDateTimeDiff(endTime.getTime()-startTime.getTime());
                                    retValue.money=0;
                                    retValue.stopDay=1;
                                }
                            }else{
                                retValue.stopTime=1440;
                                retValue.money=0;
                                retValue.stopDay=1;
                            }
                        }
                    }else{
                        retValue.stopTime=0;
                        retValue.money=0;
                        retValue.stopDay=0;
                    }
                }
            }
        }

        return retValue;
    },
    GetDateTimeDiffBefore:function (startTime, endTime) {
        var retValue = {};

        var date = new Date(startTime).getTime() - new Date(endTime).getTime();  //时间差的毫秒数

        //计算出相差天数
        var days = Math.floor(date / (24 * 3600 * 1000));
        retValue.Days = days;

        var years = Math.floor(days / 365);
        retValue.Years = years;

        var months = Math.floor(days / 30);
        retValue.Months = months;

        //计算出小时数
        var leave1 = date % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000));
        retValue.Hours = hours;

        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000));
        retValue.Minutes = minutes;

        //计算相差秒数
        var leave3 = leave2 % (60 * 1000);      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000);
        retValue.Seconds = seconds;

        var strTime = "";
        if (years >= 1) {
            strTime = years + "年前";
        } else if (months >= 1) {
            strTime = months + "个月前";
        } else if (days >= 1) {
            strTime = days + "天前";
        } else if (hours >= 1) {
            strTime = hours + "小时前";
        } else {
            strTime = minutes + "分钟前";
        }
        retValue.PutTime = strTime;
        return retValue;
    },
}